﻿using System;
using System.IO;
using System.Text;
using System.Web.UI.WebControls;
using umbraco.BasePages;
using umbraco.cms.businesslogic.member;
using umbraco.IO;


namespace Designit.Umb.Newsletter.Custom.plugins.designit.newsletter
{
    public partial class CreateNewsletterCampaign : UmbracoEnsuredPage
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            
            if (!IsPostBack)
            {
                var mailSettings = Bll.MailSettings.Get();

                iframe1.Attributes.Add("onload", "setData();");
                iframePreview.Attributes.Add("onload", "resizeIframe('iframePreview');");
                NextButton.OnClientClick = @"loadData();";

                var bounceGroup = MemberGroup.GetByName("Bounced");

                #region Panel1
                Session["step"] = 1;
                ProgressLiteral.Text = "New campaign - step 1/4";
                Repeater1.DataSource = MemberGroup.GetAll;
                Repeater1.DataBind();

                for (int i = 0; i < Repeater1.Items.Count; i++)
                {

                    var lt = (Literal)Repeater1.Items[i].FindControl("LiteralRecipents");

                    if (lt != null)
                    {
                        var numRecipients = 0;
                        foreach (var member in MemberGroup.GetByName(lt.Text).GetMembers())
                        {
                            if(!bounceGroup.HasMember(member.Id))
                            {
                                numRecipients++;
                            }
                        }
                        lt.Text = "(" + numRecipients + " recipients)";
                    }

                    lt = (Literal)Repeater1.Items[i].FindControl("LiteralName");
                    if (lt.Text == "Bounced")
                    {
                        Repeater1.Items[i].Visible = false;
                    }
                }
                #endregion

                //Panel 2
                if (Request["title"] != null)
                {
                    txtCampaignName.Text = Request["title"];
                }
                txtFrom.Text = mailSettings.SenderName;
                TxtReply.Text = mailSettings.SenderMail;
                
                using (var reader =
                    umbraco.BusinessLogic.Application.SqlHelper.ExecuteReader("select alias from newsLetterTemplate"))
                {
                    while (reader.Read())
                    {
                        ListBox1.Items.Add(reader.GetString("alias"));

                    }
                }
                checkLinkGoogle.Enabled = false;


                //check if we are in edit state
                if (Session["campaignId"] != null)
                {
                    string pageId = Session["campaignId"].ToString();
                    if (pageId.Length > 0)
                    {
                        Edit(pageId);
                    }

                }


            }


        }

        protected void CheckLinkTrackCheckedChanged(object sender, EventArgs e)
        {
            checkLinkGoogle.Enabled = checkLinkTrack.Checked;
        }

        protected override void OnInit(EventArgs e)
        {
            base.OnInit(e);

            //add buttons to umbraco pane
            var save = UmbracoPanel1.Menu.NewImageButton();
            save.ImageURL = SystemDirectories.Umbraco + "/images/editor/save.gif";
            save.Click += SaveDraftButton_Click;
            save.OnClientClick = @"loadData();";
            save.AltText = "Save";

            var testMail = UmbracoPanel1.Menu.NewImageButton();
            testMail.ID = "btnTest";
            testMail.Visible = false;
            testMail.ImageUrl = umbraco.GlobalSettings.Path + "/images/designit/newsletter/save_test.gif";
            testMail.Click += TestMailButton_Click;
            testMail.Attributes.Add("Title", "Send test mail");

            var sendMail = UmbracoPanel1.Menu.NewImageButton();
            sendMail.ID = "btnSend";
            sendMail.Visible = false;
            sendMail.ImageUrl = umbraco.GlobalSettings.Path + "/images/designit/newsletter/save_send.gif";
            sendMail.Click += SendCampaignButton_Click;
            sendMail.Attributes.Add("Title", "Send campaign");

        }

        private void Edit(string id)
        {
            using (var reader =
                umbraco.BusinessLogic.Application.SqlHelper.ExecuteReader("select * from newsletterCampaignNewsletter where id=@id",
                                                                          umbraco.BusinessLogic.Application.SqlHelper.CreateParameter("@id", Int32.Parse(id))))
            {

                while (reader.Read())
                {
                    txtCampaignName.Text = reader.GetString("camptitle");
                    txtSubjct.Text = reader.GetString("campsubject");
                    txtFrom.Text = reader.GetString("campfrom");
                    TxtReply.Text = reader.GetString("campreplyMail");
                    contentTextbox.Text = reader.GetString("campcontent");

                    if (reader.GetString("campTrack") == "true")
                    {
                        checkLinkTrack.Checked = true;
                        if (reader.GetString("campGoogle") == "true")
                            checkLinkGoogle.Checked = true;
                        else
                            checkLinkGoogle.Enabled = false;
                    }

                    var template = reader.GetString("campTemplate");
                    if (!string.IsNullOrEmpty(template))
                        ListBox1.SelectedValue = template;
                }
            }

            //check if grps are assigned to campaign
            using (var reader =
                umbraco.BusinessLogic.Application.SqlHelper.ExecuteReader("select * from newsletterCampaign2Group where campaignId=@id",
                                                                          umbraco.BusinessLogic.Application.SqlHelper.CreateParameter("@id", id)))
            {
                while (reader.Read())
                {
                    for (int i = 0; i < Repeater1.Items.Count; i++)
                    {
                        var lt = (Literal) Repeater1.Items[i].FindControl("LiteralName");
                        if (lt.Text == reader.GetString("groupName"))
                        {
                            var cb = (CheckBox) Repeater1.Items[i].FindControl("CheckboxGroup");
                            cb.Checked = true;
                        }


                    }
                }
            }
        }

        protected void NextButton_Click(object sender, EventArgs e)
        {

            if ((int)Session["step"] == 1)
            {
                pp_step2.Visible = true;
                pp_step1.Visible = false;
                BackButton.Enabled = true;

                Session["step"] = 2;
                ProgressLiteral.Text = "New campaign - step 2/4";
            }
            else if ((int)Session["step"] == 2 && ListBox1.SelectedIndex > -1)
            {
                pp_step2.Visible = false;
                pp_step3.Visible = true;
                Session["step"] = 3;
                ProgressLiteral.Text = "New campaign - step 3/4";

                iframe1.Attributes.Add("src", "/base/embedNewsletter/Emb/" + ListBox1.SelectedItem.Value + ".aspx");

            }
            else if ((int)Session["step"] == 3)
            {
                umbraco.BusinessLogic.Application.SqlHelper.ExecuteNonQuery("update newsLetterCampaignTempContent set tempContent=@Content where id=1",
                                                                            umbraco.BusinessLogic.Application.SqlHelper.CreateParameter("@Content", contentTextbox.Text));
                pp_step3.Visible = false;
                pp_step4.Visible = true;
                NextButton.Enabled = false;
                Session["step"] = 4;
                UmbracoPanel1.Menu.FindControl("btnTest").Visible = true;
                UmbracoPanel1.Menu.FindControl("btnSend").Visible = true;
                ProgressLiteral.Text = "New campaign - step 4/4";
                iframePreview.Attributes.Add("src", "/base/embedNewsletter/Embstep4/" + ListBox1.SelectedItem.Value + ".aspx");

            }
        }

        protected void BackButton_Click(object sender, EventArgs e)
        {
            if ((int)Session["step"] == 2)
            {
                pp_step1.Visible = true;
                pp_step2.Visible = false;
                BackButton.Enabled = false;
                Session["step"] = 1;
                ProgressLiteral.Text = "New campaign - step 1/4";
            }
            else if ((int)Session["step"] == 3)
            {
                umbraco.BusinessLogic.Application.SqlHelper.ExecuteNonQuery("update newsLetterCampaignTempContent set tempContent=@Content where id=1",
                                                                            umbraco.BusinessLogic.Application.SqlHelper.CreateParameter("@Content", contentTextbox.Text));
                pp_step2.Visible = true;
                pp_step3.Visible = false;
                Session["step"] = 2;
                ProgressLiteral.Text = "New campaign - step 2/4";
            }
            else
            {
                pp_step3.Visible = true;
                pp_step4.Visible = false;
                NextButton.Enabled = true;
                Session["step"] = 3;
                UmbracoPanel1.Menu.FindControl("btnTest").Visible = false;
                UmbracoPanel1.Menu.FindControl("btnSend").Visible = false;
                ProgressLiteral.Text = "New campaign - step 3/4";

            }
        }

        protected void SaveDraftButton_Click(object sender, EventArgs e)
        {
            SaveCampaign();
            Response.Redirect("editNewsletterCampaign.aspx?id=1");
        }

        protected void TestMailButton_Click(object sender, EventArgs e)
        {
            var campaignId = SaveCampaign();
            var sb = new StringBuilder();
            sb.AppendLine(@"<script type=""text/javascript"">");
            sb.AppendLine(
                ClientTools.Scripts.OpenModalWindow(string.Format("{0}/plugins/designit/newsletter/testMail.aspx?id={1}", IOHelper.ResolveUrl(SystemDirectories.Umbraco), campaignId), "Send test mail", 500, 200));
            //sb.AppendLine("top.openModal('plugins/designit/newsletter/testMail.aspx?id=" + campaignId + "', 'Send test mail', 200,500);");
            sb.AppendLine("</script>");
            Page.ClientScript.RegisterStartupScript(GetType(), "testPopUp", sb.ToString());

        }

        protected void SendCampaignButton_Click(object sender, EventArgs e)
        {
            int campaignId = SaveCampaign();
            var sb = new StringBuilder();
            sb.AppendLine(@"<script type=""text/javascript"">");
            sb.AppendLine(
                ClientTools.Scripts.OpenModalWindow(string.Format("{0}/plugins/designit/newsletter/DelaySend.aspx?id={1}", IOHelper.ResolveUrl(SystemDirectories.Umbraco), campaignId), "Send campaign", 608, 550));
            sb.AppendLine("</script>");
            Page.ClientScript.RegisterStartupScript(GetType(), "popUp", sb.ToString());

        }

        private int SaveCampaign()
        {
            string selectedTemplate;
            var contentText = "";
            var templateText = "";
            if (ListBox1.SelectedIndex > -1)
            {
                selectedTemplate = ListBox1.SelectedItem.ToString();
                contentText = contentTextbox.Text;
                var path = Bll.Helper.GetTemplateDir();
                path = Path.Combine(path, string.Format("{0}.master", ListBox1.SelectedValue));

                if (File.Exists(path))
                {
                    templateText = File.ReadAllText(path);
                }
            }
            else
            {
                selectedTemplate = "";
            }

            var track = checkLinkTrack.Checked ? "true" : "false";

            var googleTrack = checkLinkGoogle.Checked ? "true" : "false";

            if (Session["campaignId"] == null)
            {
                Session["campaignId"] = "";
            }

            if (Session["campaignId"] != null && !string.IsNullOrEmpty(Session["campaignId"].ToString()))
            {
                var id = Int32.Parse(Session["campaignId"].ToString());
                umbraco.BusinessLogic.Application.SqlHelper.ExecuteNonQuery(
                    "update newsletterCampaignNewsletter set camptitle=@title, campsubject=@subject, campstatus=@status, campfrom=@from, campreplyMail=@replyMail, campTemplate=@Template, campContent=@Content, campTemplatecontent=@campTemplatecontent, campTrack=@track, campGoogle=@google where id=@id",
                    umbraco.BusinessLogic.Application.SqlHelper.CreateParameter("@title", txtCampaignName.Text),
                    umbraco.BusinessLogic.Application.SqlHelper.CreateParameter("@subject", txtSubjct.Text),
                    umbraco.BusinessLogic.Application.SqlHelper.CreateParameter("@status", "draft"),
                    umbraco.BusinessLogic.Application.SqlHelper.CreateParameter("@from", txtFrom.Text),
                    umbraco.BusinessLogic.Application.SqlHelper.CreateParameter("@replyMail", TxtReply.Text),
                    umbraco.BusinessLogic.Application.SqlHelper.CreateParameter("@Template", selectedTemplate),
                    umbraco.BusinessLogic.Application.SqlHelper.CreateParameter("@Content", contentText),
                    umbraco.BusinessLogic.Application.SqlHelper.CreateParameter("@campTemplatecontent", templateText),
                    umbraco.BusinessLogic.Application.SqlHelper.CreateParameter("@track", track),
                    umbraco.BusinessLogic.Application.SqlHelper.CreateParameter("@google", googleTrack),
                    umbraco.BusinessLogic.Application.SqlHelper.CreateParameter("@id", id));
                SignGroupToCampaign(id);
                return id;
            }
            else
            {
                var id = umbraco.BusinessLogic.Application.SqlHelper.ExecuteScalar<int>("insert into newsletterCampaignNewsletter(camptitle, campsubject, campstatus, campfrom, campreplyMail, campTemplate, campContent, campTemplatecontent, campTrack, campGoogle) values(@title, @subject, @status, @from, @replyMail, @Template, @Content, @campTemplatecontent, @track, @google);select @@Identity",
                                                                                        umbraco.BusinessLogic.Application.SqlHelper.CreateParameter("@title", txtCampaignName.Text),
                                                                                        umbraco.BusinessLogic.Application.SqlHelper.CreateParameter("@subject", txtSubjct.Text),
                                                                                        umbraco.BusinessLogic.Application.SqlHelper.CreateParameter("@status", "draft"),
                                                                                        umbraco.BusinessLogic.Application.SqlHelper.CreateParameter("@from", txtFrom.Text),
                                                                                        umbraco.BusinessLogic.Application.SqlHelper.CreateParameter("@replyMail", TxtReply.Text),
                                                                                        umbraco.BusinessLogic.Application.SqlHelper.CreateParameter("@Template", selectedTemplate),
                                                                                        umbraco.BusinessLogic.Application.SqlHelper.CreateParameter("@Content", contentText),
                                                                                        umbraco.BusinessLogic.Application.SqlHelper.CreateParameter("@campTemplatecontent", templateText),
                                                                                        umbraco.BusinessLogic.Application.SqlHelper.CreateParameter("@track", track),
                                                                                        umbraco.BusinessLogic.Application.SqlHelper.CreateParameter("@google", googleTrack));
                SignGroupToCampaign(id);
                return id;
            }

        }

        private void SignGroupToCampaign(int id)
        {
            umbraco.BusinessLogic.Application.SqlHelper.ExecuteNonQuery("delete from newsletterCampaign2Group where campaignId=@id",
                                                                        umbraco.BusinessLogic.Application.SqlHelper.CreateParameter("@id", id));
            for (var i = 0; i < Repeater1.Items.Count; i++)
            {

                var cb = (CheckBox)Repeater1.Items[i].FindControl("CheckboxGroup");

                if (cb.Checked)
                {
                    var lt = (Literal)Repeater1.Items[i].FindControl("LiteralName");
                    umbraco.BusinessLogic.Application.SqlHelper.ExecuteNonQuery("Insert into newsLetterCampaign2Group(campaignId, groupName, groupId) values(@id, @name, @groupId)",
                                                                                umbraco.BusinessLogic.Application.SqlHelper.CreateParameter("@id", id),
                                                                                umbraco.BusinessLogic.Application.SqlHelper.CreateParameter("@name", lt.Text),
                                                                                umbraco.BusinessLogic.Application.SqlHelper.CreateParameter("groupId", MemberGroup.GetByName(lt.Text).Id));


                }


            }
        }

    }
}